<template>
  <div class="app-container">

    <el-form ref="jForm" :model="jForm" :rules="jRules" label-width="120px">
      <el-card>
        <div slot="header" class="clearfix">
          <span style="font-weight:bold;color:#1890FF;font-size:14px;">新客户端接入集群<span style="color:red;margin-left:10px">(注：要接入客户端，前提条件是客户端已经搭好，并且已运行客户端)</span></span>
        </div>
        <el-form-item label="客户端IP" prop="serverIp" :rules="{validator: validateIPAddress,required: true, trigger: 'blur'}">
          <el-input v-model="jForm.serverIp"></el-input>
        </el-form-item>
        <el-form-item label="机器名称" prop="serverIp">
          <el-input v-model="jForm.hostName"></el-input>
        </el-form-item>
        <el-form-item label="集群中台地址" prop="clusterIp" :rules="{validator: validateIPAddress,required: true, trigger: 'blur'}">
          <el-input v-model="jForm.clusterIp"></el-input>
        </el-form-item>
        <el-form-item label="CC安装路径" prop="jobPath">
          <el-input v-model="jForm.ccPath"></el-input>
        </el-form-item>
        <el-row style="margin-top:-10px;margin-bottom:10px;">
          <el-col :span="24">
            <span style="margin-left:120px;color:red;font-weight:bold;font-size:12px;">注：到bin目录(例：C:/Program Files/Bentley/ContextCapture Center/bin)</span>
          </el-col>
        </el-row>
        <el-form-item label="工作路径" prop="jobPath">
          <el-input v-model="jForm.jobPath"></el-input>
        </el-form-item>
        <el-row style="margin-top:-10px;margin-bottom:10px;">
          <el-col :span="24">
            <span style="margin-left:120px;color:red;font-weight:bold;font-size:12px;">注：请先在客户端本地建好工作目录后再添加工作路径,路径不要有空格以及中文(例：C:/jobs2)</span>
          </el-col>
        </el-row>
        <el-form-item label="引擎类型" prop="engineType">
          <el-checkbox-group v-model="checkList" @change="selectEngineType">
            <el-checkbox label="1" border>全类型</el-checkbox>
            <el-checkbox label="AT" border>空三</el-checkbox>
            <el-checkbox label="TileProduction" border>模型</el-checkbox>
            <el-checkbox label="RasterProduction" border>正摄</el-checkbox>
            <el-checkbox label="AI" border>AI</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item>
          <center>
            <el-button type="primary" @click="joinCluster">加入集群</el-button>
          </center>
        </el-form-item>
      </el-card>
    </el-form>

    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-card style="margin-top:10px;">
        <div slot="header" class="clearfix">
          <span style="font-weight:bold;color:#1890FF;font-size:14px;">查询条件设置</span>
        </div>
        <el-form-item label="客户端IP" prop="serverIp">
          <el-input
            v-model="queryParams.serverIp"
            placeholder="请输入客户端IP"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="机器名" prop="hostName">
          <el-input
            v-model="queryParams.hostName"
            placeholder="请输入机器名"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-card>
    </el-form>

    <el-card style="margin-top:10px;">
      <div slot="header" class="clearfix">
        <span style="font-weight:bold;color:#1890FF;font-size:14px;">退出集群客户端列表<span style="color:red;margin-left:10px">(注：要重新接入客户端，前提条件是客户端已经搭好，并且已运行客户端)</span></span>
      </div>
      <el-table v-loading="loading" :data="engineList" border>
        <el-table-column label="服务器IP" align="center" prop="serverIp" />
        <el-table-column label="机器名" align="center" prop="hostName" />
        <el-table-column label="引擎类型" align="center" prop="engineType" />
        <el-table-column label="引擎类型" align="center" prop="typeName" />
        <el-table-column label="加入集群时间" align="center" prop="inTime" width="120">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.inTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="退出集群时间" align="center" prop="quitTime" width="120">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.quitTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="150">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-s-promotion"
              @click="handleUpdate(scope.row)"
            >重新加入集群</el-button>
          </template>
        </el-table-column>
      </el-table>
    
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

    </el-card>

    <!-- 添加或修改引擎信息表对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="客户端IP" prop="serverIp">
          <el-input v-model="form.serverIp" disabled />
        </el-form-item>
        <el-form-item label="机器名" prop="hostName">
          <el-input v-model="form.hostName" disabled />
        </el-form-item>
        <el-form-item label="集群中台地址" prop="clusterIp" :rules="{validator: validateIPAddress,required: true, trigger: 'blur'}">
          <el-input v-model="form.clusterIp" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listEngine, getEngine, delEngine, addEngine, updateEngine } from "@/api/system/engine";
import axios from "axios";

export default {
  name: "Engine",
  data() {
    return {
      checkList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 引擎信息表表格数据
      engineList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        serverIp: null,
        hostName: null,
        onOff: null,
        engineStatus: null,
        engineType: null,
        typeName: null,
        jobPath: null,
        serverType: null,
        clusterIp: null,
        clusterIn: 2,
        inTime: null,
        quitTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        serverIp: [{ required: true, message: "客户端IP不能为空", trigger: "blur"}],
        hostName: [{ required: true, message: "机器名称不能为空",trigger: "blur"}],
        clusterIp: [{ required: true, message: "集群中台IP不能为空",trigger: "blur"}],
      },
      jForm: {
        serverIp: null,
        hostName: null,
        clusterIp: null,
        jobPath: null,
        engineType: null,
        typeName: null,
        ccPath: null,
      },
      jRules: {
        serverIp: [{ required: true, message: "客户端IP不能为空", trigger: "blur"}],
        hostName: [{ required: true, message: "机器名称不能为空",trigger: "blur"}],
        clusterIp: [{ required: true, message: "集群中台IP不能为空",trigger: "blur"}],
        jobPath: [{ required: true, message: "工作路径不能为空",trigger: "blur"}],
        ccPath: [{ required: true, message: "CC安装路径不能为空",trigger: "blur"}],
        engineType: [{ required: true, message: "引擎类型不能为空",trigger: "blur"}],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    joinCluster(){
      if(this.checkList.length==0){
        this.$message.error("请选择引擎类型!");
        return false;
      }else{
        let data = [{name:"AT",label:"空三"},{name:"RasterProduction",label:"正摄"},{name:"TileProduction",label:"模型"},{name:"AI",label:"AI"}];
        let engine_type = "";
        let type_name = "";
        let typeArray = new Array();
        let flag = 1;
        for(let i=0;i<this.checkList.length;i++){
          if(this.checkList[i]=="1"){
            engine_type = "AT,RasterProduction,TileProduction,AI";
            type_name = "全类型";
            flag = 2;
            break;
          }else{
            flag = 1;
            typeArray.push(this.checkList[i])
          }
        }

        if(flag==1){
          for(let x=0;x<typeArray.length;x++){
            if(x==0){
              engine_type = engine_type+typeArray[x];
              data.forEach(item =>{
                if(item.name == typeArray[x]){
                  type_name = type_name+item.label;
                }
              });
            }else{
              engine_type = engine_type+","+typeArray[x];
              data.forEach(item =>{
                if(item.name == typeArray[x]){
                  type_name = type_name+","+item.label;
                }
              });
            }
          }
        }
        this.jForm.engineType = engine_type;
        this.jForm.typeName = type_name;
        this.$refs["jForm"].validate(valid => {
          if (valid) {
            addEngine(this.jForm).then(response => {
              this.$modal.msgSuccess("加入集群成功");
              this.$router.push({path:"/cluster"});

              let data = {
                cluster_ip: this.jForm.clusterIp,
                server_ip: this.jForm.serverIp,
                hostname: this.jForm.hostName,
              }
              let url = "http://"+this.jForm.serverIp+":9500/joinCluster"
              axios
              .post(url,data)
              .then((data) => {})
              .catch((response) => {
                // this.$message.error("加载失败!");
              });

            });
          }
        });
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          addEngine(this.form).then(res =>{
            this.$modal.msgSuccess("重新加入集群成功");
            this.$router.push({path:"/cluster"});

            let data = {
                cluster_ip: this.form.clusterIp,
                server_ip: this.form.serverIp,
                hostname: this.form.hostName,
              }
              let url = "http://"+this.form.serverIp+":9500/joinCluster"
              axios
              .post(url,data)
              .then((data) => {})
              .catch((response) => {
                this.$message.error("加载失败!");
              });
          })
        }
      });
    },
    selectEngineType(val){
      for(let i=0;i<val.length;i++){
        if(val[i]=="1"){
          this.checkList = ['1','AT','TileProduction','RasterProduction','AI'];
          break;
        }else{
          this.checkList = val;
        }
      }
    },
    validateIPAddress(rule, value, callback){
      if (!value) {
        return callback('请输入IP地址');
      }
      const ipRegex = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;;
      if (!ipRegex.test(value)) {
        return callback('IP地址格式不正确');
      }
      const parts = value.split('.');
      const validIpAddress = parts.every(part => parseInt(part, 10) >= 0 && parseInt(part, 10) <= 255);
      if (!validIpAddress) {
        return callback('IP地址格式不正确');
      }
      callback();
    },
    /** 查询引擎信息表列表 */
    getList() {
      this.loading = true;
      listEngine(this.queryParams).then(response => {
        this.engineList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        serverIp: null,
        hostName: null,
        onOff: null,
        engineStatus: null,
        engineType: null,
        typeName: null,
        jobPath: null,
        serverType: null,
        clusterIp: null,
        clusterIn: null,
        inTime: null,
        quitTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加引擎信息表";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.title = "客户端重新加入集群";
      this.form = row;
      this.open = true;
      // this.$modal.confirm('是否确认客户端："' + row.serverIp+"("+row.hostName+")"  + '"重新加入集群？').then(function() {
      //   return addEngine(row);
      // }).then(() => {
      //   this.$modal.msgSuccess("重新加入集群成功");
      //   this.$router.push({path:"/cluster"});
      // }).catch(() => {});
    },
    
    /** 删除按钮操作 */
    handleDelete(row) {
      const serverIps = row.serverIp || this.ids;
      this.$modal.confirm('是否确认删除引擎信息表编号为"' + serverIps + '"的数据项？').then(function() {
        return delEngine(serverIps);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/engine/export', {
        ...this.queryParams
      }, `engine_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
